package com.redovation.mapdemo;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.view.MotionEvent;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private Polyline polyline;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Context context = this;

        MapsInitializer.updatePrivacyShow(context, true, true);
        MapsInitializer.updatePrivacyAgree(context, true);


        TextureMapView mapView = findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
        PolylineOptions polylineOptions =
                new PolylineOptions().width(6).color(Color.GREEN).zIndex(2);
        AMap aMap = mapView.getMap();
        polyline = aMap.addPolyline(polylineOptions);
        aMap.getUiSettings().setScrollGesturesEnabled(false);
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                polylineOptions.add(latLng);
                if (polylineOptions.getPoints().size() > 2) {
                    polylineOptions.getPoints().set(0, latLng);
                }
                polyline.setPoints(polylineOptions.getPoints());
            }
        });
        aMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            private LatLng pointLatlng;
            private int pointX;
            private int pointY;

            @Override
            public void onTouch(MotionEvent motionEvent) {
                pointX = (int) motionEvent.getX();
                pointY = (int) motionEvent.getY();
                Point point = new Point(pointX, pointY);
                pointLatlng = aMap.getProjection().fromScreenLocation(point);
                switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_MOVE://移动
                        if (polylineOptions.getPoints().size() > 2) {
                            polylineOptions.getPoints().set(0, pointLatlng);
                        }
                        polyline.setPoints(polylineOptions.getPoints());
                        break;
                }
            }
        });

    }
}